package com.me.iot.domain;

import com.me.iot.server.socket.MeIOTAcceptHandler;

import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;

/**
 * @author mingke
 * @desc Socket的相关配置信息
 * @time 2022/5/10
 */
public class MeIOTSocketConfigInfo extends MeIOTConfigInfo{
    private Integer socketPort;
    private Integer socketBufferSize;
    private Integer socketClientNum;

    /**
     * 基于TCP的物联网系统上位机需要在此处创建一个Socket服务端
     */
    @Override
    public void iotServerHandler() {
        InetSocketAddress inetSocketAddress = new InetSocketAddress(socketPort);
        try {
            final AsynchronousServerSocketChannel channel = AsynchronousServerSocketChannel.open();
            channel.bind(inetSocketAddress);
            System.out.println(this.getApplicationNameCN()+"--服务器启动完毕");
            channel.accept(channel, new MeIOTAcceptHandler(this));
        }catch(Exception e) {
            e.printStackTrace();
        }
        //弄一个线程过来的目的是不让当前这个服务端直接结束
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t.start();
    }

    public Integer getSocketPort() {
        return socketPort;
    }

    public void setSocketPort(Integer socketPort) {
        this.socketPort = socketPort;
    }

    public Integer getSocketBufferSize() {
        return socketBufferSize;
    }

    public void setSocketBufferSize(Integer socketBufferSize) {
        this.socketBufferSize = socketBufferSize;
    }

    public Integer getSocketClientNum() {
        return socketClientNum;
    }

    public void setSocketClientNum(Integer socketClientNum) {
        this.socketClientNum = socketClientNum;
    }

    @Override
    public String toString() {
        return "MeIOTSocketConfigInfo{" +
                "socketPort=" + socketPort +
                ", socketBufferSize=" + socketBufferSize +
                ", socketClientNum=" + socketClientNum +
                '}';
    }
}
